import { ref_file_info } from '../uni_comps/load_file_info/uni_comps/file_uni_info/file_uni_info';

export function bind_file_info(file: File) {
  let cur_file_info: any = {
    name: file.name,
    size: file.size,
    formattedSize: formatFileSize(file.size),
    type: file.type,
    lastModified: new Date(file.lastModified),
    extension: getFileExtension(file.name),
  };

  let key: keyof typeof ref_file_info.value;

  for (key in ref_file_info.value) {
    ref_file_info.value[key] = cur_file_info[key];
  }
}

function formatFileSize(bytes: number) {
  if (bytes === 0) return '0 Bytes';

  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function getFileExtension(filename: string) {
  return filename.slice(((filename.lastIndexOf('.') - 1) >>> 0) + 2);
}
